package com.lxr0860.lxr0860production_test.itemactivity;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.lxr0860.lxr0860production_test.R;
import com.lxr0860.lxr0860production_test.adapter.ItemDevListAdapter;
import com.lxr0860.lxr0860production_test.utils.AudioRecorderUtils;
import com.lxr0860.lxr0860production_test.utils.Contants;
import com.lxr0860.lxr0860production_test.utils.SharedPreferencesUtils;
import com.lxr0860.lxr0860production_test.view.HorizontalProgressBar;

import java.io.IOException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;


public class BluTest extends Activity implements SwipeRefreshLayout.OnRefreshListener, AdapterView.OnItemClickListener {



    /** The profile is in disconnected state */
    public static final int STATE_DISCOnNECTED= 0;
    /** The profile is in connecting state */
    public static final int STATE_COnNECTING= 1;
    /** The profile is in connected state */
    public static final int STATE_COnNECTED= 2;
    /** The profile is in disconnecting state */
    public static final int STATE_DISCOnNECTING= 3;
    public static final int BOND_NOnE= 10;
    public static final int BOND_BOnDING= 11;
    public static final int BOND_BOnDED= 12;
    private MediaPlayer mMediaPlayer;
    private TextView mTvTitle,mTvTip, mTvTime;
    private HorizontalProgressBar mProgress;
    private Button mBtnStart;

    private ListView lvBtList;
    private ItemDevListAdapter adapter;
    private SwipeRefreshLayout layoutSwipeRefresh;
    private BluetoothAdapter mBluetoothAdapter;
    private List<BluetoothDevice> list;
    private AssetManager mAssetManager;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case Contants.DIALOG_POSITIVE:
                    Intent mIntent=new Intent();
                    Bundle bundle=new Bundle();
                    bundle.putBoolean("result",true);
                    mIntent.putExtras(bundle);
                    BluTest.this.setResult(Contants.TEST_ITEM_BLUETOOTH,mIntent);
                    finish();
                    break;
                case Contants.DIALOG_NEGATIVE:
                    finish();
                    break;
            }
        }
    };
    private long mMusicTime, mMaxTime;

    private Runnable musicRunnable = new Runnable() {
        @Override
        public void run() {
            mProgress.setProgress((int) mMusicTime);
            mTvTime.setText(formatTime(mMusicTime));
            mMusicTime += AudioRecorderUtils.SPACE;
            handler.postDelayed(this, AudioRecorderUtils.SPACE);
        }
    };
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @SuppressLint("MissingPermission")
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case  BluetoothDevice.ACTION_FOUND:
                    Log.e("search","ACTION_FOUND");
                    BluetoothDevice device1 = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    Log.e("devices",device1.getName()+"=="+device1.getAddress());
                        Log.e("devicesD",device1.getName()+"=="+device1.getAddress());
                        if (device1.getName() != null && device1.getAddress() != null) {
                            if (!mBleMac.equals("")&&mBleMac.equals(device1.getAddress())) {
                                //直接连接
                                connectDev(device1);
                            }
                            int k = 0;
                            for (BluetoothDevice i : list)
                                if (i.getAddress().equals(device1.getAddress()))
                                    k++;
                            if (k == 0) {
                                list.add(device1);
                            }
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    adapter.notifyDataSetChanged();
                                }
                            });
                        }
                    break;
                case  BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
                    Log.e("search","ACTION_DISCOVERY_FINISHED");
                    layoutSwipeRefresh.setRefreshing(false);
                    break;
                case  BluetoothDevice.ACTION_BOND_STATE_CHANGED:
                    Log.e("search","ACTION_BOND_STATE_CHANGED");
                    //设备绑定状态改变
                    BluetoothDevice device2 = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    int bOndState= intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
                    switch (bOndState) {
                        case BOND_BOnDED:
                            Log.e("bind","BOND_BOnDED");
                            //收到绑定成功的通知后自动连接
                            Toast.makeText(BluTest.this, "设备已连接", Toast.LENGTH_SHORT).show();
                            mBluListLay.setVisibility(View.GONE);
                            mAudioTestLay.setVisibility(View.VISIBLE);
                            SharedPreferencesUtils.saveData(context,BleMac,device2.getAddress());
//                            connectDev(device2);
                            break;
                        case BOND_BOnDING:
                            Log.e("bind","BOND_BOnDING");
                            Toast.makeText(context, "正在连接", Toast.LENGTH_SHORT).show();
                            break;
                        case BOND_NOnE:
                            Log.e("bind","BOND_NOnE");
                            Toast.makeText(context, "断开连接", Toast.LENGTH_SHORT).show();
                            break;
                    }

                    break;
                case  BluetoothAdapter.ACTION_STATE_CHANGED:
                    int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                    switch (blueState) {
                        case BluetoothAdapter.STATE_TURNING_ON:
                            Log.e("onReceive","STATE_TURNING_ON");
                            break;
                        case BluetoothAdapter.STATE_ON:
                            Log.e("onReceive","STATE_ON");
                            searchBlu();
                            break;
                        case BluetoothAdapter.STATE_TURNING_OFF:
                            Log.e("onReceive","STATE_TURNING_OFF");
                            break;
                        case BluetoothAdapter.STATE_OFF:
                            Log.e("onReceive","STATE_OFF");
                            break;
                    }
                    break;
            }
        }
    };


    private LinearLayout mAudioTestLay;
    private LinearLayout mBluListLay;
    private String BleMac = "BluMac";
    private String mBleMac = "";

    @SuppressLint({"CommitPrefEdits", "MissingInflatedId"})
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myblu);
        lvBtList = findViewById(R.id.lv_bt_list);
        mTvTitle= (TextView) findViewById(R.id.tv_audio_title);
        mBtnStart = (Button) findViewById(R.id.btn_phone_start);
        mTvTime = (TextView) findViewById(R.id.tv_phone_test_time);
        mTvTip = (TextView) findViewById(R.id.tv_phone_tip);
        mAudioTestLay = findViewById(R.id.Lay_audioTest);
        mBluListLay = findViewById(R.id.Lay_blulist);
        mProgress = findViewById(R.id.pb_phone_test);
        list = new ArrayList<>();
        layoutSwipeRefresh = findViewById(R.id.layout_swipe_refresh);
        layoutSwipeRefresh.setOnRefreshListener(this);
        adapter = new ItemDevListAdapter(list,this);
        lvBtList.setAdapter(adapter);
        lvBtList.setOnItemClickListener(this);
        mBtnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBtnStart.setEnabled(false);
                prepareMusic();
            }
        });
        initBlu();

        mBleMac = SharedPreferencesUtils.getData(this,BleMac, "");
    }

    @SuppressLint("MissingPermission")
    private void initBlu(){
        list.clear();
        mAssetManager = getAssets();
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, 1);
        }

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        intentFilter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);
        intentFilter.addAction(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(mReceiver, intentFilter);
        searchBlu();
//        removePairDevice();
    }
    @SuppressLint("MissingPermission")
    private void searchBlu(){
        list.clear();
        layoutSwipeRefresh.setRefreshing(true);
         Set<BluetoothDevice> bondedDevices = mBluetoothAdapter.getBondedDevices();

        list.addAll(bondedDevices);
        adapter.notifyDataSetChanged();
        mBluetoothAdapter.startDiscovery();
        for (BluetoothDevice bondedDevice : bondedDevices) {
            if (bondedDevice.getAddress().equals(mBleMac)) {
                if (bondedDevice.getBondState() == BOND_BOnDED) {
                    Toast.makeText(this, "设备已连接", Toast.LENGTH_SHORT).show();
                    mBluListLay.setVisibility(View.GONE);
                    mAudioTestLay.setVisibility(View.VISIBLE);
                    SharedPreferencesUtils.saveData(this,BleMac,bondedDevice.getAddress());
                    return;
                }
                if (bondedDevice.getBondState() == BOND_BOnDING) {
                    Toast.makeText(this, "正在连接", Toast.LENGTH_LONG).show();
                    return;
                }
                connectDev(bondedDevice);
            }
        }
    }


    @Override
    public void onRefresh() {
        searchBlu();
    }

    @SuppressLint("MissingPermission")
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        BluetoothDevice device = list.get(position);
        if (device.getBondState() == BOND_BOnDED) {
            Toast.makeText(this, "设备已连接", Toast.LENGTH_SHORT).show();
            mBluListLay.setVisibility(View.GONE);
            mAudioTestLay.setVisibility(View.VISIBLE);
            SharedPreferencesUtils.saveData(this,BleMac,device.getAddress());
            return;
        }
        if (device.getBondState() == BOND_BOnDING) {
            Toast.makeText(this, "正在连接", Toast.LENGTH_LONG).show();
            return;
        }
        connectDev(device);
    }

    @SuppressLint("MissingPermission")
    private void connectDev(BluetoothDevice device) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //Android 4.4 API 19 以上才开放Bond接口
            device.createBond();
        } else {
            //API 19 以下用反射调用Bond接口
            try {
                device.getClass().getMethod("connect").invoke(device);
            } catch (Exception e) {
                Toast.makeText(this, "连接失败", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        }
    }


    private void prepareMusic() {
        AudioManager audiomanage = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        audiomanage.setMode(AudioManager.MODE_NORMAL);
        audiomanage.setStreamVolume(AudioManager.STREAM_MUSIC, 30, AudioManager.FLAG_SHOW_UI);
        if (mMediaPlayer == null) {
            mMediaPlayer = new MediaPlayer();
        }else {
            mMediaPlayer.reset();
        }
        try {
            AssetFileDescriptor fileDescriptor = mAssetManager.openFd("phone.wav");
            mMediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),
                    fileDescriptor.getStartOffset(),
                    fileDescriptor.getLength());
            mMediaPlayer.prepare();
//            mMusicTime = 0;
//            mMaxTime = mMediaPlayer.getDuration();
//            mProgress.setMax((int) mMaxTime);
            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mp.stop();
                    handler.removeCallbacks(musicRunnable);
                    mProgress.setProgress(0);
                    mTvTime.setText(formatTime(0));
                    mTvTip.setText("测试完毕");
                    Contants.showDailog(BluTest.this,
                            "测试完毕，蓝牙是否正常",handler, Gravity.TOP);
                    mBtnStart.setEnabled(true);
                }
            });
            startMusic();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void startMusic() {
        mTvTip.setText("正在进行蓝牙测试");
        mTvTime.setText("已开始播放");
        if (!mMediaPlayer.isPlaying()) {
            handler.post(musicRunnable);
            mMediaPlayer.start();
        }
    }

    private void realseMusic() {
        if (mMediaPlayer != null) {
            mMediaPlayer.reset();
            mMediaPlayer.release();
        }
    }
    private String formatTime(long time) {
        SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");
        String formatTime = formatter.format(time);
        return formatTime;
    }

    @SuppressLint("MissingPermission")
    @Override
    protected void onDestroy() {
        super.onDestroy();
        realseMusic();
        unregisterReceiver(mReceiver);
        mBluetoothAdapter.disable();
    }


    //得到配对的设备列表，清除已配对的设备
    @SuppressLint("MissingPermission")
    public void removePairDevice(){
        if(mBluetoothAdapter!=null){
            Set<BluetoothDevice> bondedDevices = mBluetoothAdapter.getBondedDevices();
            for(BluetoothDevice device : bondedDevices ){
                unpairDevice(device);
            }
        }
    }

    //反射来调用BluetoothDevice.removeBond取消设备的配对
    private void unpairDevice(BluetoothDevice device) {
        try {
            Method m = device.getClass()
                    .getMethod("removeBond", (Class[]) null);
            m.invoke(device, (Object[]) null);
        } catch (Exception e) {
//            Log.e(TAG, e.getMessage());
        }
    }

}
